<template>
  <div class="w-full h-full Login" style="background: #fff">
    <Nav class="fixed top-0 w-full z-10" />

    <div class="px-4 py-1 text-center w-full bg-white" style="height: 100%; padding-top: 64px; padding-bottom: 20px">
      <h1 class="my-5 text-2xl">{{ translateTitle('Base.login.WMS手持移动终端系统') }}</h1>
      <van-form class="mt-2">
        <van-cell-group inset>
          <van-field
            ref="refUser"
            v-model="formData.USER_ID"
            class="rounded-full my-4"
            label=""
            label-align="center"
            left-icon="manager"
            :name="translateTitle('Base.login.用户名')"
            :placeholder="translateTitle('Base.login.请输入用户名')"
            @keydown="confirm($event, 'refUser')"
          />
          <van-field
            ref="refPw"
            v-model="formData.PASSWORD"
            class="rounded-full my-4"
            label=""
            label-align="center"
            left-icon="lock"
            :name="translateTitle('Base.login.密码')"
            :placeholder="translateTitle('Base.login.请输入密码')"
            type="password"
            @keydown="confirm($event, 'refPw')"
          />
          <van-field
            v-model="formData.LANGUAGE"
            class="rounded-full my-4"
            label=""
            left-icon="setting"
            :name="translateTitle('Base.login.语言')"
            :placeholder="translateTitle('Base.login.请选择语言')"
            @click="clickBtn('LANGUAGE')"
            @keydown="confirm($event, 'refUser')"
          />
        </van-cell-group>
        <div class="my-6">
          <van-button block round style="background: #152777; margin-bottom: 20px" type="primary" @click="loginBtn">
            {{ translateTitle('Base.login.登录') }}
          </van-button>

          <van-button block class="btn" round style="margin-bottom: 20px" @click="clearIp">
            {{ translateTitle('Base.login.清空IP') }}
          </van-button>

          <!-- <div class="absolute bottom-2 w-full bottom"> -->
          <!-- <div class="my-3" style="margin-top: 50px">版本V1.0</div> -->
          <!-- </div> -->
          <div class="bottom-2 w-full bottom" style="width: 95%; margin-left: 2%">
            <div class="my-3 bottom-2">
              <span>{{ translateTitle('Base.login.版本') }}</span>
              <span>{{ loginVersion }}</span>
            </div>
          </div>
        </div>
      </van-form>
    </div>
    <Select :columns="columns" :show-picker="Picker" @close="close" />
  </div>
</template>
<script>
  import { defineComponent, toRefs, reactive, ref } from 'vue'
  import { useStore } from 'vuex'
  import Select from '../components/Select'
  import Nav from '../components/nav'
  import { damsPost } from '../api/api.js'
  import isEmpty from 'lodash/isEmpty'
  // import { gp } from '@vui'
  import { setStorage } from '@/utils/tools'
  import { useRouter } from 'vue-router'
  import { toAppsPage } from '@project/config'
  import { Field, Form, CellGroup, button } from 'vant'
  // import { useStorage } from '@common/hooks/useStorage'
  import { Dialog } from 'vant'
  import { translateTitle } from '@/utils/i18n'
  import canvasFP from '@/utils/canvasFP.js'
  import i18n from '@commonProject/i18n'
  import { GFCD } from '@/utils/utils'

  export default defineComponent({
    name: 'Login',
    components: { Nav, Select, [Form.name]: Form, [CellGroup.name]: CellGroup, [Field.name]: Field, [button.name]: button },
    setup() {
      const store = useStore()
      // let Storage = useStorage()
      // 登陆数据
      var loginData = reactive({
        logoImg: '../styles/imgs/logo-name.png',
        pickImg: '../styles/imgs/pick.jpg',
        formData: {
          USER_ID: '',
          PASSWORD: '',
          LANGUAGE_CODE: '',
          LANGUAGE: '',
        },
        Picker: false,
        columns: [],
        version: '',
        loginVersion: '',
      })
      // 本地走test mac
      setStorage('MACADDRESS', '78:8E:33:2F:ED:7E')

      //版本号
      loginData.loginVersion = GFCD('login', 'version')
      // 拿mac地址
      window.$CIMC.getMacAddress((res) => {
        if (res.code == '200') {
          setStorage('MACADDRESS', res.data)
        }
      })

      //const host = window.location.host

      //console.log('host11111', host)

      //版本号升级
      const isUpgradeFunc = (res) => {
        console.log('返回数据了--', res)
        if (res.code == '200') {
          const arr = res.data.split(',')
          loginData.version = arr[1]
          // const protocol = window.location.protocol
          // const host = window.location.host
          //var url = `${protocol}//${host}/pda/apk_download/CIMC_WMSV2_PDA_${arr[2]}.apk`
          if (arr[0] == 'true') {
            Dialog.alert({
              title: translateTitle('Base.login.版本更新'),
              message: translateTitle('Base.login.app版本升级提示'),
            }).then(() => {
              // console.log('这就是地址哈哈哈哈哈', url)

              //请求DAMS接口获取下载地址
              getdownLoadUrl('dams.app.conf.query', (url) => {
                console.log('r', url)
                window.open(url, '_blank')
              })
              // window.open(url, '_blank') //打开下载地址页面
            })
          }
        }
      }

      //获取下载地址
      function getdownLoadUrl(downloadMethod, callback) {
        damsPost({ '#LIMIT#': '1', '#PAGE_SIZE#': '10', APP_PARAMS_CN_DESC: '', APP_PARAMS_CODE: 'wms.pda.download' }, downloadMethod)
          .then((res) => {
            console.log('sss', res.data['dams.app.conf.query'].data[0].APP_PARAMS_VAL)
            callback(res.data['dams.app.conf.query'].data[0].APP_PARAMS_VAL)
          })
          .catch((err) => {
            window.$CIMC.playMusic('ERROR', err.msg)
          })
      }

      //打开摄像头
      // window.$CIMC.openCapture = (res) => {
      //   console.log('res--', res)
      //   if (res.code == '200') {
      //     setStorage('GETCAPTUREDATA', res.data)
      //   }
      // }
      //是否更新版本号
      window.$CIMC.isUpgrade(isUpgradeFunc)

      //使用store
      store.dispatch('pdaNav/setnavData', { title: translateTitle('Base.login.登录'), leftArrow: false, notMenu: true })

      //回车事件
      let refUser = ref(null)
      let refPw = ref(null)
      function confirm($event, ref) {
        if ($event.keyCode == 13) {
          if (ref == 'refUser') {
            refPw.value.focus()
          }
        }
      }

      const router = useRouter()

      getLanguage()
      // 登录请求接口
      async function login(data) {
        return store.dispatch('user/login', data)
      }
      async function loginBtn() {
        if (isEmpty(loginData.formData.USER_ID)) {
          window.$CIMC.playMusic('ERROR', translateTitle('Base.login.请输入用户名'))
          return
        }
        if (isEmpty(loginData.formData.PASSWORD)) {
          window.$CIMC.playMusic('ERROR', translateTitle('Base.login.请输入密码'))
          return
        }
        if (isEmpty(loginData.formData.LANGUAGE_CODE)) {
          window.$CIMC.playMusic('ERROR', translateTitle('Base.login.请选择语言'))
          return
        }
        //设想 APP_CODE
        let APP_CODE = 'WMS'
        let fingerprint = `${canvasFP({ uid: loginData.formData.USER_ID || '' }).hash}`
        store.dispatch('tmp/setFingerprint', fingerprint)
        login({
          ...loginData.formData,
          'FINGER-MARK': fingerprint,
          VERIFY_CODE: '',
          LOGIN_ENTRANCE: 'PDA',
          APP_CODE: APP_CODE,
        })
          .then((res) => {
            //toUpdatePassWordPage为Y 则必须修改密码再登录
            if (res.toUpdatePassWordPage == 'Y') {
              loginData.formData.PASSWORD = ''
              return window.$CIMC.playMusic('ERROR', res.passwordWarnTime)
            }

            // passwordWarnTime有值提示修改密码 登录
            if (!isEmpty(res.passwordWarnTime)) {
              window.$CIMC.playMusic('ERROR', res.passwordWarnTime)
            } else {
              window.$CIMC.playMusic('OK', translateTitle('Base.login.登录成功'))
            }

            store.dispatch('user/setAppCode', APP_CODE)
            setTimeout(() => {
              if (toAppsPage) {
                store.dispatch('user/setLoginData', loginData.formData)
                router.push('/apps')
              } else {
                router.push('/')
              }
            }, 10)
          })
          .catch((err) => {
            window.$CIMC.playMusic('ERROR', err.msg)
            loginData.formData.PASSWORD = ''
          })
      }
      //清空IP
      function clearIp() {
        //获取浏览器信息
        let msg = navigator.userAgent
        //判断是否为安卓浏览器
        if (msg.indexOf('Android') > -1 || msg.indexOf('Linux') > -1) {
          //错误音提示
          window.$CIMC.playMusic('ERROR', '')
          //安卓端提示用户是否清除IP退出
          Dialog.confirm({
            //title: '是否退出',
            message: '确认清除IP退出APP',
            showConfirmButton: true,
            showCancelButton: true,
          })
            .then(() => {
              // console.log('确认')
              window.$CIMC.delIpMsg()
            })
            .catch(() => {
              // console.log('取消')
            })
        } else {
          window.$CIMC.playMusic('ERROR', '请在移动端设备上操作')
        }
      }
      // 登录请求接口
      function getLanguage() {
        let method = 'dams.language.query'
        damsPost({ '#LIMIT#': '1', '#PAGE_SIZE#': '10' }, method)
          .then((res) => {
            let arr = []
            for (let obj of res.data[method].data) {
              arr.push({
                key: obj.LANGUAGE_CODE,
                name: obj.LANGUAGE_DESC,
              })
              loginData.columns = arr
            }
            loginData.formData.LANGUAGE_CODE = arr[0].key
            loginData.formData.LANGUAGE = arr[0].name
          })
          .catch((err) => {
            window.$CIMC.playMusic('ERROR', err.msg)
          })
      }
      // 点击下拉选
      function clickBtn(key) {
        if (key == 'LANGUAGE') {
          loginData.Picker = true
        }
      }
      function close(flage, value) {
        // value为空的话证明是取消按钮。直接关闭下拉选即可
        if (isEmpty(value)) {
          loginData.Picker = flage
          return
        }
        // 否则是确定按钮，需要设置数据处理

        loginData.formData.LANGUAGE = value.name
        i18n.global.locale = value.key
        loginData.formData.LANGUAGE_CODE = value.key
        loginData.Picker = flage
      }

      return {
        loginBtn,
        confirm,
        ...toRefs(loginData),
        refUser,
        refPw,
        close,
        clickBtn,
        getLanguage,
        translateTitle,
        clearIp,
      }
    },
  })
</script>
<style lang="scss">
  html,
  body {
    height: 100%;
  }
  .Login {
    .van-cell {
      background: #f5f3f3;
      padding: 0.3rem 1rem !important;
    }
    .van-field__control {
      text-indent: 10px !important;
      padding: 0.1rem 0rem !important;
    }
    .van-badge__wrapper {
      color: var(--btn-comfirm-back) !important;
      font-size: 1rem !important;
    }

    .bottom {
      width: calc(100% - 2rem);
    }
    .van-button--primary {
      border-radius: 5rem !important;
      height: 3rem !important;
      background: rgb(21, 39, 119) !important;
    }
    .van-cell__title > label {
      font-size: 1rem;
      width: 100% !important;
    }
    .van-field__error-message {
      font-size: 10px !important;
    }
    .van-cell__title > label {
      font-size: 18px !important;
      width: 100% !important;
    }

    .van-cell-group {
      margin: var(--van-cell-group-inset-padding) !important;
    }
    .van-cell-group {
      background: none;
    }
    .van-button--default,
    .btn {
      background-color: #eee;
    }
  }
</style>
